package com.radioapp.liaoliaobao.module.user.login;

import android.Manifest;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.jaydenxiao.common.base.BaseFragment;
import com.jaydenxiao.common.base.BaseRiggerFragment;
import com.jaydenxiao.common.baseapp.AppManager;
import com.jaydenxiao.common.baseapp.BaseApplication;
import com.jaydenxiao.common.basebean.LoginEvent;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jaydenxiao.common.sharepref.SharePref;
import com.jaydenxiao.common.token.TokenUtil;
import com.jkb.fragment.rigger.rigger.Rigger;
import com.radioapp.liaoliaobao.R;
import com.radioapp.liaoliaobao.bean.user.LoginBean;
import com.radioapp.liaoliaobao.bean.user.UserBean;
import com.radioapp.liaoliaobao.constant.Constants;
import com.radioapp.liaoliaobao.constant.Global;
import com.radioapp.liaoliaobao.module.index.MainFragment;
import com.radioapp.liaoliaobao.module.lifecyclerObserver.RxPermissionsFragmentObserver;
import com.radioapp.liaoliaobao.module.user.forgetPwd.ForgetPwdFragment;
import com.radioapp.liaoliaobao.uihelper.UiHelper;
import com.radioapp.liaoliaobao.utils.BaiDuMapUtil;
import com.radioapp.liaoliaobao.utils.EaseUIUtils;
import com.radioapp.liaoliaobao.utils.RegexUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.utils.LogUtils;

/**
 * 功能： 登录
 * 描述
 * Created by yue on 2019-07-15
 */
public class LoginFragment extends BaseRiggerFragment<LoginView, LoginPresenter> implements LoginView,
        RxPermissionsFragmentObserver.PermissionCallBack {
    @BindView(R.id.et_login_account)
    EditText etLoginAccount;
    @BindView(R.id.et_login_pwd)
    EditText etLoginPwd;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.iv_wx)
    ImageView ivWx;
    @BindView(R.id.iv_qq)
    ImageView ivQq;
    @BindView(R.id.iv_wb)
    ImageView ivWb;

    private RxPermissionsFragmentObserver rxPermissionsObserver;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        //

        //环信退出
//        EaseUIUtils.loginOut();
        //清除数据
        SharePref.clear();
       // SharePref.remove("token_type");
       // SharePref.remove("access_token");
       // SharePref.remove("login_bean");
       // SharePref.remove("userInfo");

        //权限申请
        rxPermissionsObserver = new RxPermissionsFragmentObserver(this);
        getLifecycle().addObserver(rxPermissionsObserver);
        rxPermissionsObserver.setCallBack(this);
        rxPermissionsObserver.requestPermissions(0, Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA);
    }

    @Override
    public void tokenInvalidRefresh() {

    }


    @OnClick({R.id.tv_commit, R.id.tv_register, R.id.tv_forget, R.id.iv_wx, R.id.iv_qq, R.id.iv_wb})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_commit: //登录
                if (checkPhone(etLoginAccount.getText().toString(), etLoginPwd.getText().toString())) {
                    mPresenter.login(etLoginAccount.getText().toString(), etLoginPwd.getText().toString(),
                            SharePref.getString(Constants.LONGITUDE,"0"),
                            SharePref.getString(Constants.LATITUDE,"0"));
                }
                break;
            case R.id.tv_register: //注册
                UiHelper.shwRegisterFrament(mActivity);
                break;
            case R.id.tv_forget: //忘记密码
                UiHelper.showForgetPwdFragment(mActivity);
                break;
            case R.id.iv_wx:  //wx

                break;
            case R.id.iv_qq: //qq
                break;
            case R.id.iv_wb:  //wb
                break;
            default:
              break;
        }
    }


    /**
     * 检查手机号.
     **/
    private boolean checkPhone(String phone, String pwd) {
        if (TextUtils.isEmpty(phone)) {
            ToastUitl.showLong(getString(R.string.login_hint_account));
            return false;
        }
        if (TextUtils.isEmpty(pwd)) {
            ToastUitl.showLong(getString(R.string.login_hint_pwd));
            return false;
        }

        if (!RegexUtil.isMobile(phone)) {
            ToastUitl.showLong(getString(R.string.code_correct_phone_hint));
            return false;
        }
        if (!RegexUtil.isPassword(pwd)) {
            ToastUitl.showLong(getString(R.string.login_pwd_correct));
            return false;
        }


        return true;
    }

    @Override
    public void success(LoginBean loginBean) {
        // BaseApplication.isTokenRefresh = true;
        //保存登录信息
        Global.saveLoginBean(loginBean);
        //保存必要的用户信息
        UserBean userBean=new UserBean();
        userBean.setGender(loginBean.getGender());
        userBean.setVerified_at(loginBean.getVip_ended_at());
        userBean.setInvite_code(loginBean.getInvite_code());
        userBean.setInvite_code(loginBean.getInvite_code());
        Global.saveUserInfo(userBean);
        //保存token
        TokenUtil.putTokenType(loginBean.getToken_type());
        TokenUtil.putAccessToken(loginBean.getAccess_token());
        //登录通知
        EventBus.getDefault().post(new LoginEvent());


        EaseUIUtils.login(String.valueOf(loginBean.getEasemob_id()), loginBean.getEasemob_password());

        if (loginBean.getGender() == 0) {
            //选择性别
            UiHelper.showSelectGenderFragment(mActivity);
            return;
        } else if (loginBean.getGender() == 1) {
            //邀请码
            if (TextUtils.isEmpty(loginBean.getInvite_code()) && TextUtils.isEmpty(loginBean.getVip_ended_at())) {
                UiHelper.showCodeFragment(mActivity);
                return;
            }
        }

       UiHelper.showMainFragment(mActivity);
        Rigger.getRigger(this).close();

    }

    @Override
    public void granted(int type) {
    }

    @Override
    public void shouldShowRequestPermissionRationale() {

    }

    @Override
    public void other() {
    }


    private long exitTime;

    /**
     * 退出应用
     *
     * @return
     */
    public boolean onRiggerBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(mActivity, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();

            return true;
        } else {
            try {
                FragmentManager childFragmentManager = ((FragmentActivity) mActivity).getSupportFragmentManager();
                List<Fragment> fragments = childFragmentManager.getFragments();
                if (fragments.size() > 0) {
                    for (Fragment fragment : fragments) {
                        Rigger.getRigger(fragment).close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            AppManager.getAppManager().AppExit(mActivity, true);
            return false;
        }


    }

}
